import store from '@/store'
import Vue from "vue";
import cssValue from "@/util/themes/css-value";
export const knownThemes = ['dark', 'light'];
const themes = {
  dark: '#091022',
  light: 'rgba(233,238,245,1)'
};
const footer = {
  dark: '#FFFFFF',
  light: '#000000',
}
const icon = {
  dark: '#FFFFFF',
  light: '#666666',
}
const elSwitch = {
  dark: {
    on:'#3370FF',
    down:'#8590B3'
  },
  light: {
    on:'#3370FF',
    down:'#CCCCCC'
  },
}
const tableChangeIcon = {
  dark: {
    narrow:'icon-table-c2',
    broad:'icon-table-c1'
  },
  light: {
    narrow:'icon-table-c6',
    broad:'icon-table-c4'
  },
}
const disElSwitch = {
  dark: {
    on:'#19387F',
    down:'#333333'
  },
  light: {
    on:'#3370FF',
    down:'#CCCCCC'
  },
}
class Themes {
  constructor() {
    const tasks = knownThemes.map(n => {
      return this.preloadTheme(n)
    });
    Promise.all(tasks).then(_ => {
      this._watchSystemChanges();
      // const userPref = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
      const useTheme =
        // localStorage.getItem("theme")
        // || userPref ||
         knownThemes[0];
      this.select(useTheme);
    });
  }

  preloadTheme(name) {
    return import(`@/assets/styles/${name}.scss`)
  }

  select(name) {
    if (name && !themes[name]) {
      throw new Error(`"${name}" has not been defined as a theme.`);
    }
    store.commit('SET_THEME', name)
    // echart[name]()
    let body = document.body;
    body.style.background = themes[name];
    body.setAttribute("data-theme", name);
    localStorage.setItem("theme", name);
    this.initCssValue(name)
  }
  initCssValue(theme){
    const flag = {light:0,dark:1}
    const root = document.querySelector(":root");
    const keys = Object.keys(cssValue)
    keys.forEach(key=>{
      root.style.setProperty(key, cssValue[key][flag[theme]]);
    })

  }
  getSwitch(){
    return elSwitch[store.getters.theme]
  }
  getTableChangeIcon(){
    return tableChangeIcon[store.getters.theme]
  }
  getFooter(){
    return footer[store.getters.theme]
  }
  _watchSystemChanges() {
    if (!window.matchMedia) return;
    window.matchMedia('(prefers-color-scheme: dark)').addListener(e => {
      if (e.matches) {
        this.select('dark');
      } else {
        this.select('light');
      }
    });
  }
  icon(){
    return icon[store.getters.theme]
  }
  get names() {
    return knownThemes;
  }
}

export default {
  install(Vue){
    Vue.prototype.$themes = new Themes();
  }
}
